import cfg from '@/config/app';
import store from "../store";
import {
	toLogin,
	logout,
	checkLogin
} from '@/utils/login.js';
import Cache from '@/utils/cache.js';
/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = cfg.HTTP_REQUEST_URL,
		header = cfg.HEADER;
	if (!noAuth) {
		//登录过期自动登录
		let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
		let curRoute = routes[routes.length - 1].route 
		if (!store.state.app.token && !checkLogin()) {
			// #ifndef MP
			//toLogin();
			// #endif
			// #ifdef MP

			// #endif
			uni.showToast({
				title: '请登录后使用',
				icon: 'none',
				mask: true,
				duration: 2000
			})

			if (curRoute !== 'pages/login/login') {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
			return false;
			//return Promise.reject('请登录后在使用');
		}
	}
	if (store.state.app.token) header[cfg.TOKENNAME] = store.state.app.token;
	
	//header[TOKENNAME] = 'Bearer 5a7ac0a300ead1b2cbb8c9150bfab02e';
	return new Promise((reslove, reject) => {
		//data.invite_code = Cache.get('invite_code') || '';
		uni.request({
			url: Url + '/api'+ url,
			method: method || 'GET',
			header: header,
			data: data || {},
			timeout:600000,
			success: (res) => {
				if (res.data.code == 401 ){
					store.commit('LOGOUT');
					uni.showToast({
						title: '请登录后使用',
						icon: 'none',
						mask: true,
						duration: 2000
					});
					uni.navigateTo({
						url: '/pages/login/login'
					})
					return false;
				}
				if (res.data.data && res.data.gzde === 1) {
					try {
						res.data.data = JSON.parse(decompress(res.data.data));
					} catch (e) {
						res.data.data = decompress(res.data.data);
					}
				}

				if (noVerify)
					reslove(res.data, res);
				else if (res.data.status == 200)
					
					reslove(res.data, res);
				else if (res.data.code == 0) {
					reject(res.data);
				} else
					reject(res.data || '系统错误1'+res);
			},
			fail: (msg) => {
				let data = {
					info: '请求失败',
					status: 1 //1没网
				}

				reject(data);
			
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;